package com.xl.basic.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.constraints.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;


/**
 * 入参时间格式转换器
 */
@Configuration
public class DateTimeConfig {
    /**
     * 字符串转localDateTime，支持所有常见的格式
     *
     * @return Converter
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        class MyConverter implements Converter<String, LocalDateTime> {
            @Override
            public LocalDateTime convert(@NotNull String s) {
                if (StrUtil.isBlank(s)) {
                    return null;
                }

                return LocalDateTimeUtil.of(DateUtil.parse(s));
            }
        }
        return new MyConverter();
    }

    /**
     * 字符串转localDate，支持所有常见的格式
     *
     * @return Converter
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        class MyConverter implements Converter<String, LocalDate> {
            @Override
            public LocalDate convert(@NotNull String s) {
                if (StrUtil.isBlank(s)) {
                    return null;
                }
                return LocalDateTimeUtil.parseDate(s);
            }
        }
        return new MyConverter();
    }

    /**
     * 字符串转Date，支持所有常见的格式
     *
     * @return Converter
     */
    @Bean
    public Converter<String, Date> DateConverter() {
        class MyConverter implements Converter<String, Date> {
            @Override
            public Date convert(@NotNull String s) {
                if (StrUtil.isBlank(s)) {
                    return null;
                }
                return DateUtil.parse(s);
            }
        }

        return new MyConverter();
    }

}
